package com.zbkj.service.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.novel.NovelAuthoritytEntity;
import com.zbkj.common.model.novel.NovelEntity;
import com.zbkj.common.model.novel.NovelRollChapterEntity;
import com.zbkj.common.model.together.UserTogether;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.NovelAddRequest;
import com.zbkj.common.request.NovelListRequest;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.response.*;
import com.zbkj.service.dao.NovelDao;
import com.zbkj.service.dao.UserDao;
import com.zbkj.service.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 小说对象表 接口实现类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * @author: 大粽子
 * +----------------------------------------------------------------------
 * @date Mon Apr 22 15:31:27 CST 2024
 * +----------------------------------------------------------------------
 * @email stivepeim@outlook.com
 * +----------------------------------------------------------------------
 */

@Service("novelService")
public class NovelServiceImpl extends ServiceImpl<NovelDao, NovelEntity> implements NovelService {
    @Resource
    NovelDao novelDao;

    @Autowired
    UserDao userDao;

    @Autowired
    NovelCategoryService novelCategoryService;

    @Autowired
    NovelRollChapterService novelRollChapterService;

    @Autowired
    NovelAuthorityService novelAuthorityService;

    @Autowired
    UserService userService;
    @Autowired
    UserTogetherService userTogetherService;

    @Autowired
    TransactionTemplate transactionTemplate;

    @Override
    public Integer add(NovelAddRequest request) {
        if(request.getArticlename()!=null) {
            LambdaQueryWrapper<NovelEntity> lqw = new LambdaQueryWrapper<>();
            lqw.eq(NovelEntity::getArticlename, request.getArticlename());
            if(ObjectUtil.isNotNull(novelDao.selectOne(lqw)))
                throw new CrmebException("该书已存在");
        }

//        Integer userId = 2;
        Integer userId = userService.getUserId();
        if(userId==0){
            throw new CrmebException("用户未登录");
        }
        request.setUId(userId);
        NovelEntity novel = new NovelEntity();
        BeanUtils.copyProperties(request,novel);

        NovelAuthoritytEntity novelAuthoritytEntity = new NovelAuthoritytEntity();
        novelAuthoritytEntity.setNovel_id(novel.getId());
        novelAuthoritytEntity.setUid(userId);

        Boolean execute = transactionTemplate.execute(e->{
            novelDao.insert(novel);

            if(request.getTogetherId()!=null){
                UserTogether u = new UserTogether();
                u.setId(request.getTogetherId());
                u.setTargetId(novel.getId());
                userTogetherService.updateById(u);
            }

            novelAuthoritytEntity.setNovel_id(novel.getId());
            novelAuthorityService.save(novelAuthoritytEntity);
//        novel.setAuthorityIds(novelAuthoritytEntity.getId());
            return Boolean.TRUE;
        });

        if(execute){
            return novel.getId();
        }else {
            throw new CrmebException("数据处理失败");
        }
    }

    @Override
    public String addAuthority(Integer uid, Integer novelId) {
        NovelEntity novel = novelDao.selectById(novelId);
        if(ObjectUtil.isNull(novel)){
            throw  new CrmebException("书不存在");
        }


//        Integer userId =2;
        Integer userId = userService.getUserId();

        if(novel.getUId()!=userId){
            throw new CrmebException("不是书的创建者");
        }
//        novel.setAuthorityIds(novel.getAuthorityIds()+","+uid);
//        novelDao.updateById(novel);



        LambdaQueryWrapper<NovelAuthoritytEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(NovelAuthoritytEntity::getNovel_id,novelId);
        lqw.eq(NovelAuthoritytEntity::getUid,uid);
        if(ObjectUtil.isNotNull(novelAuthorityService.getOne(lqw))){
            return "该用户已有权限";
        }

        NovelAuthoritytEntity authorityt = new NovelAuthoritytEntity();
        authorityt.setNovel_id(novelId);
        authorityt.setUid(uid);
        novelAuthorityService.save(authorityt);
        return "添加权限成功";
    }

    @Override
    public String delAuthority(Integer uid, Integer novelId) {
        NovelEntity novel = novelDao.selectById(novelId);
        if(ObjectUtil.isNull(novel)){
            throw  new CrmebException("书不存在");
        }

//        Integer userId =2;
        Integer userId = userService.getUserId();

        if(novel.getUId()!=userId){
            throw new CrmebException("不是书的创建者");
        }
        LambdaQueryWrapper<NovelAuthoritytEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(NovelAuthoritytEntity::getNovel_id,novelId);
        lqw.eq(NovelAuthoritytEntity::getUid,uid);
        novelAuthorityService.remove(lqw);
        return "删除权限成功";
    }

    @Override
    public List<NovelListResponse> findByName(String novelName) {
        LambdaQueryWrapper<NovelEntity> lqw = new LambdaQueryWrapper<>();
        lqw.like(NovelEntity::getArticlename,novelName);
        lqw.eq(NovelEntity::getIsShow,1);
        List<NovelEntity> list = novelDao.selectList(lqw);
        List<NovelListResponse> responseList = new ArrayList<>();
        list.forEach(item ->{
            NovelListResponse response = new NovelListResponse();
            BeanUtils.copyProperties(item,response);
            response.setAuthor(userDao.getNameById(item.getUId()));
            responseList.add(response);
        });
        return responseList;
    }

    /**
     * 模糊查询小说
     *
     * @param request
     * @param keyword
     * @return
     */
    @Override
    public PageInfo<NovelListResponse> findByKeyword(PageParamRequest request, String keyword) {
        Page<NovelListResponse> pageInfo = PageHelper.startPage(request.getPage(), request.getLimit());
        List<NovelEntity> list = novelDao.findByKeyword(keyword);
        List<NovelListResponse> responseList = new ArrayList<>();
        list.forEach(item ->{
            NovelListResponse response = new NovelListResponse();
            BeanUtils.copyProperties(item,response);
            response.setAuthor(userDao.getNameById(item.getUId()));
            responseList.add(response);
        });
        return CommonPage.copyPageInfo(pageInfo, responseList);
    }


    @Override
    public List<NovelListResponse> mylist() {
//        Integer userId = 2;
        Integer userId = userService.getUserId();

        if(userId==0)
            throw new CrmebException("请先登录");

        LambdaQueryWrapper<NovelEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(NovelEntity::getUId,userId);
        List<NovelEntity> list = novelDao.selectList(lqw);

        List<NovelListResponse> responseList = new ArrayList<>();
        list.forEach(e ->{
            NovelListResponse response = new NovelListResponse();
            BeanUtils.copyProperties(e,response);
            responseList.add(response);
        });
        return responseList;
    }

    @Override
    public List<NovelAllChaptResponse> getGarbage(Integer id) {
        LambdaQueryWrapper<NovelRollChapterEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(NovelRollChapterEntity::getNovelId,id);
        lqw.eq(NovelRollChapterEntity::getIsOpen,0);
        lqw.eq(NovelRollChapterEntity::getIsDel,1);
        List<NovelRollChapterEntity> allChapterList = novelRollChapterService.list(lqw);

        List<NovelAllChaptResponse> responseList = new ArrayList<>();
        NovelEntity novel = novelDao.selectById(id);
        allChapterList.forEach(e->{
            NovelAllChaptResponse novelDetailChapter = new NovelAllChaptResponse();
            novelDetailChapter.setName(e.getChapterName());
            novelDetailChapter.setChapterid(e.getId());
            novelDetailChapter.setChapter(novel.getTotalChapter());
            novelDetailChapter.setIndex(e.getChapterNum());
            responseList.add(novelDetailChapter);
        });
        return responseList;
    }

    public List<NovelListResponse> myAuthor() {
//        Integer userId = 2;
        Integer userId = userService.getUserId();

        if(userId==0)
            throw new CrmebException("请先登录");

        LambdaQueryWrapper<NovelAuthoritytEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(NovelAuthoritytEntity::getUid,userId);
        List<NovelAuthoritytEntity> list = novelAuthorityService.list(lqw);

        List<NovelListResponse> responseList = list.stream().map(
                e->{
                    NovelListResponse response = new NovelListResponse();
                    BeanUtils.copyProperties(novelDao.selectById(e.getNovel_id()),response);
                    return response;
                }
        ).collect(Collectors.toList());

        return responseList;
    }

    @Override
    public List<AuthorityListResponse> showAuthority(Integer novelId) {
        List<NovelAuthoritytEntity> list = novelAuthorityService.getAllByNovelId(novelId);
        List<AuthorityListResponse> responseList = new ArrayList<>();
        list.forEach(item ->{
            User user = userService.getById(item.getUid());
            AuthorityListResponse response = new AuthorityListResponse();
            response.setAvatar(user.getAvatar());
            response.setName(user.getNickname());
            response.setUid(item.getUid());
            responseList.add(response);
        });
        return responseList;
    }

    @Override
    public List<NovelListResponse> index() {
        QueryWrapper<NovelEntity> lqw = new QueryWrapper<NovelEntity>();
        List<NovelEntity> list = novelDao.selectList(lqw);
        List<NovelListResponse> responseList = new ArrayList<>();
        list.forEach(item ->{
            NovelListResponse response = new NovelListResponse();
            response.setId(item.getId());
            response.setIntro(item.getIntro());
            response.setArticlename(item.getArticlename());
            response.setUrlImg(item.getUrlImg());
            response.setAuthor(userDao.getNameById(item.getUId()));
            responseList.add(response);
        });

        return responseList;
    }

    @Override
//    @Transactional
    public NovelDetailResponse getDetail(Integer id) {
        NovelEntity novel = novelDao.selectById(id);
        NovelDetailResponse novelDetailResponse = new NovelDetailResponse();
        novelDetailResponse.setName(novel.getArticlename());
        novelDetailResponse.setPic(novel.getUrlImg());
        novelDetailResponse.setAuthor(userDao.getNameById(novel.getUId()));
        novelDetailResponse.setIntro(novel.getIntro());
        novelDetailResponse.setId(id);

        if(novel.getStatus().equals(1)){
            novelDetailResponse.setStatus("完结");
        }else {
            novelDetailResponse.setStatus("连载");
        }

        if (novel.getLength() > 10000) {
            novelDetailResponse.setWordCount(novel.getLength().toString()+"万");
        }else {
            novelDetailResponse.setWordCount(novel.getLength().toString());
        }

        novelDetailResponse.setC_name(novelCategoryService.getNameById(novel.getCatId()));

        List<NovelRollChapterEntity> list = novelRollChapterService.getlastZJById(id);
        if(list.isEmpty()){
            novelDetailResponse.setLasttime(novel.getUpdateTime());
            novelDetailResponse.setLastzj("无");
        }else {
            novelDetailResponse.setLasttime(list.get(0).getUpdateTime());
            novelDetailResponse.setLastzj(list.get(0).getChapterName());
            List<NovelDetailChapter> responseList = new ArrayList<>();
            list.forEach(item ->{
                NovelDetailChapter novelDetailChapter= new NovelDetailChapter();
                novelDetailChapter.setId(item.getId());
                novelDetailChapter.setIndex(item.getChapterNum());
                novelDetailChapter.setChapter(novel.getTotalChapter());
                novelDetailChapter.setName(item.getChapterName());
                responseList.add(novelDetailChapter);
            });
            novelDetailResponse.setLastzjlist(responseList);

        }

        return novelDetailResponse;
    }

    @Override
    public PageInfo<NovelListResponse> index(NovelListRequest listRequest) {

        LambdaQueryWrapper<NovelEntity> lqw = new LambdaQueryWrapper<>();
        Page<NovelListResponse> responsePage = PageHelper.startPage(listRequest.getPage(), listRequest.getLimit());
        if(listRequest.getCid()!=null){
            lqw.eq(NovelEntity::getCatId,listRequest.getCid());
        }
        //过滤
        lqw.eq(NovelEntity::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        lqw.eq(NovelEntity::getIsShow, Constants.COMMON_IS_FILED_ONE);
        //根据修改时间进行排序
        lqw.orderByDesc(NovelEntity::getUpdateTime);
        List<NovelEntity> list = novelDao.selectList(lqw);
        List<NovelListResponse> responseList = new ArrayList<>();
        list.forEach(item ->{
            NovelListResponse response = new NovelListResponse();
            response.setId(item.getId());
            response.setIntro(item.getIntro());
            response.setArticlename(item.getArticlename());
            response.setUrlImg(item.getUrlImg());
            response.setAuthor(userDao.getNameById(item.getUId()));
            response.setAvatar(userDao.getAvatar(item.getUId()));
            responseList.add(response);
        });

        return CommonPage.copyPageInfo(responsePage, responseList);
    }

    @Override
    public List<NovelAllChaptResponse> getAllDraft(Integer id) {
        LambdaQueryWrapper<NovelRollChapterEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(NovelRollChapterEntity::getNovelId,id);
        lqw.eq(NovelRollChapterEntity::getIsOpen,0);
        lqw.eq(NovelRollChapterEntity::getIsDel,0);
        List<NovelRollChapterEntity> allChapterList = novelRollChapterService.list(lqw);

        List<NovelAllChaptResponse> responseList = new ArrayList<>();
        NovelEntity novel = novelDao.selectById(id);
        allChapterList.forEach(e->{
            NovelAllChaptResponse novelDetailChapter = new NovelAllChaptResponse();
            novelDetailChapter.setName(e.getChapterName());
            novelDetailChapter.setChapterid(e.getId());
            novelDetailChapter.setChapter(novel.getTotalChapter());
            novelDetailChapter.setIndex(e.getChapterNum());
            responseList.add(novelDetailChapter);
        });
        return responseList;
    }

    @Override
    public List<NovelAllChaptResponse> getAllChapter(Integer id) {

        LambdaQueryWrapper<NovelRollChapterEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(NovelRollChapterEntity::getNovelId,id);
        lqw.eq(NovelRollChapterEntity::getIsOpen,1);
        List<NovelRollChapterEntity> allChapterList = novelRollChapterService.list(lqw);

        List<NovelAllChaptResponse> responseList = new ArrayList<>();
        NovelEntity novel = novelDao.selectById(id);
        allChapterList.forEach(e->{
            NovelAllChaptResponse novelDetailChapter = new NovelAllChaptResponse();
            novelDetailChapter.setName(e.getChapterName());
            novelDetailChapter.setChapterid(e.getId());
            novelDetailChapter.setChapter(novel.getTotalChapter());
            novelDetailChapter.setIndex(e.getChapterNum());
            responseList.add(novelDetailChapter);
        });
        return responseList;
    }
/**
     * Novel列表查询
     * @param request 默认是是体类 根据自己需求修改或者创建自己的request
     * @param pageParamRequest 分页参数对象
     * @return
     */
//    @Override
//    public PageUtils queryPage(NovelEntity request, PageParamRequest pageParamRequest) {
//        PageHelper.startPage(pageParamRequest.getPageNum(), pageParamRequest.getPageSize());
//
//        //列表查询 Novel 类的多条件查询
//        LambdaQueryWrapper<Novel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        Novel model = new Novel();
//        BeanUtils.copyProperties(request, model);
//        lambdaQueryWrapper.setEntity(model);
//        return dao.selectList(lambdaQueryWrapper);
//    }

}
